// WebSocketService.js
class WebSocketService {
    constructor() {
        this.socket = null;
        this.heartbeatInterval = null;
        this.heartbeatTimeout = null;
        this.heartbeatTime = 5000; // 心跳间隔时间，单位：毫秒
        this.eventCallbacks = {};
    }

    connect(url) {
        this.socket = new WebSocket(url);

        this.socket.onopen = () => {
            console.log('WebSocket 连接已打开');
            this.startHeartbeat();
            this.triggerEvent('open');
        };

        this.socket.onmessage = (event) => {
            // console.log('接收到消息:', event.data);
            if (event.data === 'pang') {
                clearTimeout(this.heartbeatTimeout);
            } else {
              this.triggerEvent('message', event.data);
            }

        };

        this.socket.onclose = () => {
            console.log('WebSocket 连接已关闭');
            this.stopHeartbeat();
            this.triggerEvent('close');
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket 发生错误:', error);
            this.stopHeartbeat();
            this.triggerEvent('error', error);
        };
    }

    send(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(message);
        }
    }

    close() {
        if (this.socket) {
            this.stopHeartbeat();
            this.socket.close();
        }
    }

    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            if (this.socket && this.socket.readyState === WebSocket.OPEN) {
                this.socket.send('ping');
                this.heartbeatTimeout = setTimeout(() => {
                    console.log('心跳超时，关闭连接');
                    this.socket.close();
                }, this.heartbeatTime);
            }
        }, this.heartbeatTime);
    }

    stopHeartbeat() {
        clearInterval(this.heartbeatInterval);
        clearTimeout(this.heartbeatTimeout);
    }

    on(event, callback) {
        if (!this.eventCallbacks[event]) {
            this.eventCallbacks[event] = [];
        }
        this.eventCallbacks[event].push(callback);
    }

    triggerEvent(event, data) {
        if (this.eventCallbacks[event]) {
            this.eventCallbacks[event].forEach((callback) => callback(data));
        }
    }
}

const webSocketService = new WebSocketService();
export default webSocketService;

